package com.supermap.application.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.supermap.application.dao.BaseAppDao;
import com.supermap.application.dao.BaseDaoImpl;
import com.supermap.application.dao.MacroPeriodDao;
import com.supermap.application.entity.TMacroPeriod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName MacroPeriodService
 * @Description 报告期
 * @Author HEKE
 * @Date 2019/2/26 14:05
 */
@Service
public class MacroPeriodService {

    @Autowired
    @PersistenceContext
    private EntityManager entityManager;

    @Autowired
    private MacroPeriodDao macroPeriodDao;

    /**
     * 根据报告期类型查询
     * @param reportType
     * @return
     */
    public JSONObject findPeriodByReportType(Integer reportType){
        BaseAppDao<TMacroPeriod,Integer> macroPeriodDao2 = new BaseDaoImpl<>(TMacroPeriod.class,entityManager);
        //查询字段
        String hql = "from TMacroPeriod t where t.reportType = ?";
        List<TMacroPeriod> list = macroPeriodDao2.queryEntity(hql,TMacroPeriod.class,reportType);
        List result1 = new ArrayList();
        List result2 = new ArrayList();
        JSONObject finalresult = new JSONObject();
       for (int i = 0 ; i<list.size(); i++){
           JSONObject jsonObject = new JSONObject();
           TMacroPeriod m = list.get(i);
           jsonObject.put("name",m.getName());
           jsonObject.put("year",m.getYear());
           jsonObject.put("month",m.getMonth());
           jsonObject.put("reportTypeName",m.getReportTypeName());

           result1.add(jsonObject);
       }
        String sql = "select max(t.year),max(t.month),min(t.year),min(t.month) from T_MACRO_PERIOD t where t.report_type = ?";
        List<Object[]> query = macroPeriodDao2.query(sql, reportType);
        for (int j = 0; j<query.size(); j++){
            Object[] objects = query.get(j);
            String maxYear = objects[0] + "";
            String maxMonth = objects[1] + "";
            String minYear = objects[2] + "";
            String minMOnth = objects[3] + "";
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("maxYear",maxYear);
            jsonObject.put("maxMonth",maxMonth);
            jsonObject.put("minYear",minYear);
            jsonObject.put("minMOnth",minMOnth);
            result2.add(jsonObject);
        }

        finalresult.put("timeInfo",result1);
        finalresult.put("maxAndMin",result2);
        return finalresult;
    }
}
